<template>
    <div class="register">
      <div class="banner">
        <van-swipe :autoplay="3000">
        <van-swipe-item v-for="(image, index) in banners" :key="index" @click="gotoUrl(image.url)">
          <van-image :src="image.image" fit="cover" />
        </van-swipe-item>
      </van-swipe>
      </div>
      <div class="register-form">
          <van-cell-group>
              <van-field v-model="nickname" left-icon="contact" placeholder="请填写昵称"  />
            <van-field v-model="mobile" left-icon="phone-o" placeholder="请输入手机号"  />
            <van-field v-model="smsCode" center clearable left-icon="passed" placeholder="请输入短信验证码">
              <van-button slot="button" size="small" :disabled="iscounting > 0" type="info" @click="sendSMS(mobile)">发送验证码<span v-if="iscounting>0">({{iscounting}})</span></van-button>
            </van-field>
            <van-field v-model="password" left-icon="bag-o" placeholder="请填写密码"  />
            <van-cell icon="location-o" is-link @click="pickAddress" :value="areas" />
          </van-cell-group>
          <div class="submit-btn">
            <van-button type="danger" size="large" @click="bindMobile">立即注册</van-button>
            <van-button class="margin-top" type="default" block  @click="onCloseRegister">暂不注册</van-button>
          </div>
      </div>
      
      <van-popup v-model="showAddressPicker" position="bottom">
      <van-picker
        ref="addPicker"
        :loading="addressLoading"
        :show-toolbar="true"
        :columns="addressColumns"
        @cancel="areaCancel"
        @change="areaChange"
        @confirm="setAddress"
      />
    </van-popup>
     <van-popup class="transbackground" :close-on-click-overlay="false" v-model="showRewardSend">
      <div class="popimgbox">
        <van-image
          width="20rem"
          height="20rem"
          fit="contain"
          :src="rewardImage"
          @click="hideRewardSend"
        />
      </div>
    </van-popup>
    </div>
</template>
<script>
import axios from "axios";
import utils from '../utils';


let areaList = null;
let areaTree = {};
let loaded = false;
let areaDelay = 0;
let interval=0;
export default {
  props: {
    lists: { type: Array }
  },
  data() {
    return {
        banners:[],
        nickname:'',
        smsCode: "",
        mobile: "",
        password: "",
        pickedAreas: [],
        iscounting:0,
        addressLoading: true,
        showAddressPicker: false,
        addressColumns: [
            {
            values: [],
            defaultIndex: 0
            },
            {
            values: [],
            defaultIndex: 0
            },
            {
            values: [],
            defaultIndex: 0
            }
        ],
        showRewardSend: false,
        rewardImage: '/static/red-packet.png',
        isSubmiting: false
    };
  },
  computed: {
    member() {
      return this.$store.state.userinfo;
    },
    areas() {
      let vals = this.pickedAreas;
      return vals.length > 0 ? vals.join("/") : "请选择地区";
    },
  },
  mounted() {
      this.loadData();
      interval = setInterval(()=>{
        if(this.iscounting>0){
            this.iscounting -= 1;
        }
        if(this.member && this.member.nickname && !this.nickname){
            this.nickname = this.member.nickname.substring(0,8)
          }
      },1000);
  },
  destroyed() {
    loaded = false;
    areaList = null;
    areaTree = {};
    clearInterval(interval)
  },
  methods: {
      loadData() {
          this.$api.post('common/advs',{flag:'register'}).then(json=>{
              this.banners = utils.fixListImage(json.data);
          })
      },
      closeRegister(){
        this.$store.commit('setRegisterState',0)
      },
    loadAddress() {
      loaded = true;
      axios
        .get("static/area.json", { baseURL: "/" })
        .then(res => {
          areaList = res.data;
          this.initAddress();
          this.addressLoading = false;
        })
        .catch(() => {
          //console.log(err)
          this.$toast.fail("地区信息加载失败");
          loaded = false;
        });
    },
    initAddress() {
      areaTree = utils.sortAddressTree(areaList);

      this.$refs.addPicker.setColumnValues(0, areaTree["00"]);

      const areas = [];
      if (this.member.province && areaTree[this.member.province]) {
        this.$refs.addPicker.setColumnValue(0, this.member.province);
      }

      let province = this.$refs.addPicker.getColumnValue(0);
      if (province && areaTree[province]) {
        this.$refs.addPicker.setColumnValues(1, areaTree[province]);
        areas.push(province)
      }
      if (this.member.city) {
        this.$refs.addPicker.setColumnValue(1, this.member.city);
      }
      let city = this.$refs.addPicker.getColumnValue(1);
      if (city && areaTree[city]) {
        this.$refs.addPicker.setColumnValues(2, areaTree[city]);
        areas.push(city)
      }else{
        this.$refs.addPicker.setColumnValues(2, []);
      }
      if (this.member.county) {
        this.$refs.addPicker.setColumnValue(2, this.member.county);
        areas.push(this.member.county)
      }
      this.pickedAreas = areas;
    },
    areaCancel() {
      this.showAddressPicker = false;
    },
    pickAddress() {
      this.showAddressPicker = true;
      if (!loaded) {
        this.loadAddress();
      }
    },
    areaChange(picker, values, idx) {
      if (!loaded) return;
      clearTimeout(areaDelay);
      areaDelay = setTimeout(() => {
        if (idx < 1 && areaTree[values[0]]) {
          picker.setColumnValues(1, areaTree[values[0]]);
        }
        if (idx < 2 && areaTree[values[1]]) {
          picker.setColumnValues(2, areaTree[values[1]]);
        }
      }, 400);
    },
    setAddress(values) {
      this.showAddressPicker = false;
      this.pickedAreas = values;
    },
    bindMobile() {
      if(this.isSubmiting)return;
      if(!this.nickname){
        this.$toast.fail('请填写昵称')
        return
      }
      if(!this.mobile){
        this.$toast.fail('请填写手机号码')
        return
      }
      if(this.member.mobile_bind && this.mobile ==  this.member.mobile){
        this.$toast.fail('手机号码未变更')
        return
      }
      if(!this.mobile.match(/^1[3-9]\d{9}$/)){
        this.$toast.fail('手机号码格式错误')
        return
      }
      if(!this.smsCode){
        this.$toast.fail('请填写验证码')
        return
      }
      if(!this.password){
        this.$toast.fail('请填写密码')
        return
      }
      if(!this.pickedAreas.length){
        //this.$toast.fail('请选择地区')
        //return
      }
      this.isSubmiting=true
      this.$api.post('member/mobile_register',
      {
          nickname:this.nickname,
          mobile:this.mobile,
          code:this.smsCode,
          password:this.password,
          areas: this.pickedAreas.join('/')
      }).then(result=>{
        this.isSubmiting=false
        this.$toast.success(result.msg||'注册成功');
        
        if(result.data && result.data.is_set_agent){
          if(result.data.image){
            this.rewardImage = utils.fixImageUrl(result.data.image)
          }
          this.showRewardSend=true
        }else{
          this.$store.dispatch("updateUserinfo");
          this.$store.commit('setRegisterState',0)
        }
      }).catch(err=>{
        this.isSubmiting=false
        this.$toast.fail(err.msg||'注册失败');
        this.smsCode = ''
      })
    },
    hideRewardSend(){
      this.showRewardSend = false
      
      this.$store.dispatch("updateUserinfo");
       this.$store.commit('setRegisterState',0)
      this.$router.push('/member/agent')
    },
    sendSMS(mobile) {
      if(!mobile){
        this.$toast.fail('请填写手机号码')
        return
      }
      if(!mobile.match(/^1[3-9]\d{9}$/)){
        this.$toast.fail('手机号码格式错误')
        return
      }
      this.$api.post('member/smscode',{mobile:mobile}).then(result=>{
        this.$toast.success(result.msg||'发送成功');
        this.iscounting = 60
      }).catch(err=>{
        this.$toast.fail(err.msg||'发送失败');
      })
    },
    onCloseRegister(){
      this.$store.commit('setRegisterState',0)
    }
  }
  
}
</script>
<style lang="scss" scpoed>
.register{
  background: rgba(0,0,0,.5);
  .banner{
      min-height: 100px;
  }
  .register-form{
      margin:30px 20px;
      padding: 10px;
      background: #fff;
      border-radius: 5px;
      .submit-btn{
        margin:20px 0;
        width:auto;
      }
  }

  .van-cell-group{
    .van-cell{
      border:0;
      border-radius:5px;
      background:#eee;
      margin:10px 0;
    }
  }
   .popimgbox,.transbackground{
    background:transparent;
    text-align: center;
  }
}
</style>